package com.gmrz.uas.plugin.sm2;

import org.bouncycastle.asn1.x509.AlgorithmIdentifier;
import org.bouncycastle.crypto.params.AsymmetricKeyParameter;
import org.bouncycastle.crypto.params.ECPrivateKeyParameters;
import org.bouncycastle.operator.ContentSigner;

import java.io.OutputStream;
import java.security.SignatureException;

/**
 * Created by zhangchao on 4/12/18.
 */
public class SM2ContentSigner implements ContentSigner {

    private byte[] sm2Prikey;

    private SM2SignatureOutputStream signatureOutPutStream;

    public SM2ContentSigner(byte[] sm2Prikey){
        this.sm2Prikey = sm2Prikey;
        this.signatureOutPutStream = new SM2SignatureOutputStream(sm2Prikey);
    }

    public SM2ContentSigner(AsymmetricKeyParameter prikeyParameter) throws Exception {
        if(prikeyParameter instanceof ECPrivateKeyParameters){
            ECPrivateKeyParameters sm2PrikeyParameter = (ECPrivateKeyParameters)prikeyParameter;
            byte[] privkeybytes = sm2PrikeyParameter.getD().toByteArray();
            sm2Prikey = new byte[32];
            System.arraycopy(privkeybytes, privkeybytes[0]==0?1:0, sm2Prikey, 0, 32);
            this.signatureOutPutStream = new SM2SignatureOutputStream(sm2Prikey);
        }else{
            throw new Exception("prikeyParameter is not ECPrivateKeyParameters");
        }
    }

    public AlgorithmIdentifier getAlgorithmIdentifier() {
        return SM2.SM2_ALOGITHM_IDENTIFIER;
    }

    public OutputStream getOutputStream() {
        return signatureOutPutStream;
    }

    public byte[] getSignature() {
        try {
            return signatureOutPutStream.getSignature();
        } catch (SignatureException e) {
            e.printStackTrace();
        }
        return null;
    }
}
